<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课程ID" prop="courseId">
        <el-select v-model="queryParams.courseId" filterable remote reserve-keyword placeholder="请输入课程ID"
          :remote-method="getCoursesByCourseId" :loading="courseLoading" style="width: 240px">
          <el-option v-for="item in courseList" :key="item.courseId" :label="item.courseName" :value="item.courseId" />
        </el-select>
      </el-form-item>
      <el-form-item label="学生" prop="studentId">
        <el-select v-model="queryParams.studentId" filterable remote reserve-keyword placeholder="请输入学生编号"
          :remote-method="getStudentsByUserName" :loading="studentLoading" style="width: 240px">
          <el-option v-for="item in studentList" :key="item.userId" :label="item.nickName" :value="item.userId" />
        </el-select>
      </el-form-item>
      <el-form-item label="考勤日期" prop="attendanceDate">
        <el-date-picker clearable v-model="queryParams.attendanceDate" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择考勤日期" style="width: 240px;">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="考勤状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择考勤状态" clearable style="width: 240px;">
          <el-option v-for="dict in attendance_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="年级" prop="deptId">
        <el-tree-select v-model="queryParams.deptId" :data="enabledDeptOptions"
          :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择归属年级"
          check-strictly default-expand-all style="width: 240px;" />
      </el-form-item>
      <el-form-item label="班级" prop="postId">
        <el-select v-model="queryParams.postId" placeholder="请选择班级" clearable style="width: 240px;">
          <el-option v-for="item in postIdList" :key="item.postId" :label="item.postName" :value="item.postId" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['manage:attendance:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['manage:attendance:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['manage:attendance:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['manage:attendance:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="attendanceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="考勤记录ID" align="center" prop="attendanceId" />
      <el-table-column label="课程ID" align="center" prop="courseId" />
      <el-table-column label="课程名称" align="center" prop="courseId" width="210">
        <template #default="scope">
          <span>
            {{
              courseAll.find(course => course.courseId === scope.row.courseId)?.courseName || '未知课程'
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="学生" align="center" prop="studentId">
        <template #default="scope">
          <span>
            {{
              studentAll.find(student => student.userId === scope.row.studentId)?.nickName || '未知学生'
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="考勤日期" align="center" prop="attendanceDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.attendanceDate, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="考勤状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="attendance_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="年级" align="center" prop="deptId">
        <template #default="scope">
          <span>
            {{
              courseAll.find(course => course.courseId === scope.row.courseId)?.dept?.deptName || '未知年级'
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="班级" align="center" prop="postId">
        <template #default="scope">
          <span>
            {{
              courseAll.find(course => course.courseId === scope.row.courseId)?.post?.postName || '未知班级'
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:attendance:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:attendance:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改考勤记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="attendanceRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="课程ID" prop="courseId">
          <el-select v-model="form.courseId" filterable remote reserve-keyword placeholder="请输入课程ID"
            :remote-method="getCoursesByCourseId" :loading="courseLoading" style="width: 240px">
            <el-option v-for="item in courseList" :key="item.courseId" :label="item.courseName"
              :value="item.courseId" />
          </el-select>
        </el-form-item>
        <el-form-item label="学生" prop="studentId">
          <el-select v-model="form.studentId" filterable remote reserve-keyword placeholder="请输入学生编号"
            :remote-method="getStudentsByUserName" :loading="studentLoading" style="width: 240px">
            <el-option v-for="item in studentList" :key="item.userId" :label="item.nickName" :value="item.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="考勤日期" prop="attendanceDate">
          <el-date-picker clearable v-model="form.attendanceDate" type="datetime" value-format="YYYY-MM-DD HH:mm"
            format="YYYY-MM-dd HH:mm" placeholder="请选择考勤日期和时间" style="width: 240px;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="考勤状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择考勤状态" style="width: 240px">
            <el-option v-for="dict in attendance_status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年级" prop="deptId">
          <el-tree-select v-model="form.deptId" disabled :data="enabledDeptOptions"
            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请先选择课程"
            check-strictly default-expand-all style="width: 240px;" />
        </el-form-item>
        <el-form-item label="班级" prop="postId">
          <el-select v-model="form.postId" disabled placeholder="请先选择课程" clearable style="width: 240px;">
            <el-option v-for="item in postIdList" :key="item.postId" :label="item.postName" :value="item.postId" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Attendance">
import { listAttendance, getAttendance, delAttendance, addAttendance, updateAttendance } from "@/api/manage/attendance";
import { allCourse, allClass } from "@/api/manage/course";
import { allStudent, deptTreeSelect } from "@/api/system/user";

const { proxy } = getCurrentInstance();
const { attendance_status } = proxy.useDict('attendance_status');

const attendanceList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const studentLoading = ref(false)
const studentList = ref([]);
const courseLoading = ref(false)
const courseList = ref([]);
const courseAll = ref([]);
const studentAll = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    courseId: null,
    studentId: null,
    attendanceDate: null,
    status: null,
    deptId: null,
    postId: null,
  },
  rules: {
    courseId: [
      { required: true, message: "课程ID不能为空", trigger: "blur" }
    ],
    studentId: [
      { required: true, message: "学生不能为空", trigger: "blur" }
    ],
    attendanceDate: [
      { required: true, message: "考勤日期不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "考勤状态不能为空", trigger: "change" }
    ],
    deptId: [
      { required: true, message: "年级不能为空", trigger: "blur" }
    ],
    postId: [
      { required: true, message: "班级不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

// 传入的参数userName查询相关学生，通过allStudent接口查询所有学生
function getStudentsByUserName(queryParams) {
  if (queryParams) {
    studentLoading.value = true;
    allStudent({ userName: queryParams }).then(response => {
      studentLoading.value = false;
      studentList.value = response.rows;
    });
  } else {
    studentList.value = null;
  }
}


// 传入的参数courseId查询相关学生，通过allCourse接口查询所有课程
function getCoursesByCourseId(queryParams) {
  if (queryParams) {
    courseLoading.value = true;
    allCourse({ courseId: queryParams }).then(response => {
      courseLoading.value = false;
      courseList.value = response.data;
    });
  } else {
    courseList.value = null;
  }
}
getStudentsByUserName();



// 得到所有学生列表
function getAllStudent() {
  allStudent().then(response => {
    studentAll.value = response.rows;
  });
}
getAllStudent();

// 得到所有课程列表
function getAllCourse() {
  allCourse().then(response => {
    courseAll.value = response.data;
  });
}
getAllCourse();


const postIdList = ref([]);

// 班级下拉框数据，获取所有班级
function getAllClass() {
  allClass().then(response => {
    postIdList.value = response.data;
    // console.log(postIdList.value);
  });
}
getAllClass();


const deptOptions = ref(undefined);
const enabledDeptOptions = ref(undefined);

/** 查询年级下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
    enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(response.data)));
  });
};
getDeptTree()

/** 过滤禁用的年级 */
function filterDisabledDept(deptList) {
  return deptList.filter(dept => {
    if (dept.disabled) {
      return false;
    }
    if (dept.id == 101) {
      return false;
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children);
    }
    return true;
  });
};



/** 查询考勤记录列表 */
function getList() {
  loading.value = true;
  listAttendance(queryParams.value).then(response => {
    attendanceList.value = response.rows.filter(row => {
      const student = studentAll.value.find(student => student.userId === row.studentId);
      return student;
    });
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    attendanceId: null,
    courseId: null,
    studentId: null,
    attendanceDate: null,
    status: null,
    deptId: null,
    postId: null,
    remark: null,
    createTime: null
  };
  proxy.resetForm("attendanceRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.attendanceId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加考勤记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _attendanceId = row.attendanceId || ids.value
  getAttendance(_attendanceId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改考勤记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["attendanceRef"].validate(valid => {
    if (valid) {
      allStudent({ userId: form.value.studentId }).then(response => {
        const student = response.rows.find(item => item.userId === form.value.studentId);
        if (student) {
          // 检查学生的 deptId 和 postId 是否与表单中的值一致
          const studentDeptId = student.deptId;
          const studentPostId = student.postIds?.[0]; // postIds 是一个数组，取第一个值
          if (studentDeptId !== form.value.deptId || studentPostId !== form.value.postId) {
            proxy.$modal.msgError("该学生不在课程所在班级");
            return; // 阻止提交
          }
        } else {
          proxy.$modal.msgError("未找到该学生信息");
          return; // 阻止提交
        }
        if (form.value.attendanceId != null) {
          updateAttendance(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          addAttendance(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _attendanceIds = row.attendanceId || ids.value;
  proxy.$modal.confirm('是否确认删除考勤记录编号为"' + _attendanceIds + '"的数据项？').then(function () {
    return delAttendance(_attendanceIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/attendance/export', {
    ...queryParams.value
  }, `attendance_${new Date().getTime()}.xlsx`)
}

watch(
  () => form.value.courseId, // 使用 form.value.courseId
  (newVal) => {
    if (title.value === "添加考勤记录") { // 添加条件
      if (newVal) {
        const course = courseList.value.find(item => item.courseId === newVal);
        if (course) {
          // 更新表单的年级和班级
          form.value.deptId = course.deptId || null;
          form.value.postId = course.postId || null;
        } else {
          form.value.deptId = null;
          form.value.postId = null;
        }
      } else {
        form.value.deptId = null;
        form.value.postId = null;
      }
    }
  }
);

getList();
</script>
